package com.tn.service.login.impl;

import com.tn.auth.utils.TokenUtil;
import com.tn.controller.alarm.common.constants.Constants;
import com.tn.controller.alarm.common.enums.CommonCodeEnum;
import com.tn.controller.alarm.common.model.user.vo.UserVO;
import com.tn.dao.login.ILogInDao;
import com.tn.exception.CommonException;
import com.tn.exception.DatabaseOperationFailedException;
import com.tn.service.login.ILonInService;
import com.tn.service.vehicle.IVehicleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录service实现类
 *
 * @program: tn_aucy_java
 * @author: yangjiayao
 * @create: 2021/12/22
 */
@Slf4j
@Service
public class LogInServiceImpl implements ILonInService {
    /**
     * 数据库交互Dao
     */
    ILogInDao logInDao;

    /**
     * 装载车DAO
     */
    IVehicleService vehicleService;

    /**
     * 自动注入
     *
     * @param logInDao logInDao
     */
    @Autowired
    public void setLogInDao(ILogInDao logInDao) {
        this.logInDao = logInDao;
    }

    /**
     * 自动注入
     *
     * @param vehicleService vehicleService
     */
    @Autowired
    public void setVehicleService(IVehicleService vehicleService) {
        this.vehicleService = vehicleService;
    }

    @Override
    public Map<String, Object> logIn(String userName, String passWord) throws CommonException {
        UserVO user = logInDao.queryUserInfoByName(userName);
        if (null == user) {
            throw new CommonException(CommonCodeEnum.NOT_EXISTS_USER.getCode(),
                    CommonCodeEnum.NOT_EXISTS_USER.getMessage());
        }
        boolean permit = passWord.equals(user.getPassword());
        if (!permit) {
            throw new CommonException(CommonCodeEnum.INVALID_PASSWORD.getCode(),
                    CommonCodeEnum.INVALID_PASSWORD.getMessage());
        }
        Map<String, Object> resultPermit = new HashMap<>();
        resultPermit.put(Constants.USER_CHECK_IS_SUPER, user.getIsSuperuser());
        TokenUtil.addTokenInfo(resultPermit, user.getUserId());
        return resultPermit;
    }

    @Override
    public void logout(String userName) throws DatabaseOperationFailedException {
        UserVO user = logInDao.queryUserInfoByName(userName);
        if (user != null) {
            TokenUtil.tokenList.remove(String.valueOf(user.getUserId()));
            // 装载车司机退出登录时修改装载车为空闲状态
            vehicleService.unboundDriver(userName);
        }
    }
}
